import json
from flask import Blueprint, request, jsonify
from model.testcase import Testcase
from utils.log_util import logger
from model import engine
from sqlalchemy.orm import Session

# 测试用例蓝图
testcase_bp = Blueprint('testcase_bp', __name__, url_prefix='/api/testcase')


@testcase_bp.route('/add', methods=['POST'])
def add():
    """
    新增
    :return:
    """
    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    # 解析请求数据
    req_data = request.json
    logger.info(f'请求体数据：{req_data}')

    # 实例化模型对象
    testcase = Testcase(**req_data)
    logger.info(testcase)

    # 写入数据库
    with Session(engine) as session:
        session.add(testcase)
        session.commit()

    # 组装响应信息
    resp.update({'success': True,
                 'msg': '新增成功！',
                 'data': {'Hi': req_data.get('name')}})

    return jsonify(resp)


@testcase_bp.route('/delete', methods=['POST'])
def delete():
    """
    删除
    :return:
    """

    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    # 解析请求数据
    req_data = request.args
    logger.info(req_data)

    if not req_data:
        resp.update({'msg': '缺少用例编号参数！'})
        return jsonify(resp)

    # 删除记录
    case_id = int(req_data.get('id'))
    with Session(engine) as session:
        # 查询表记录
        case = session.query(Testcase).filter_by(id=case_id).first()
        logger.info(case)
        if case is not None:
            # 删除表记录
            session.delete(case)
            session.commit()

            resp.update({'success': True, 'msg': '删除成功！'})
        else:
            resp.update({'msg': f'删除失败，编号{case_id}的测试用例不存在！'})

    return jsonify(resp)


@testcase_bp.route('/update', methods=['POST'])
def update():
    """
    修改
    :return:
    """

    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    # 解析请求信息
    req_data = request.json
    logger.info(f'更新操作请求信息：{req_data}')

    # 获取测试用例ID编号
    case_id = req_data.get('id')
    if not case_id:
        logger.warning('缺少ID信息')
        resp.update({'msg': '缺少ID信息'})
    else:
        # 修改表记录
        with Session(engine) as db_session:
            db_session.query(Testcase).filter_by(id=case_id).update(req_data)
            db_session.commit()

            resp.update({'success': True, 'msg': '更新成功！'})

    return jsonify(resp)


@testcase_bp.route('/list', methods=['GET'])
def list():
    """
    查询
    :return:
    """

    resp = {
        'success': False,
        'msg': '',
        'data': []
    }

    # 查询所有表记录
    with Session(engine) as session:
        cases = session.query(Testcase).all()
        logger.info(cases)

        data = []
        for c in cases:
            data.append(c.as_dict())
        logger.info(data)
        resp.update({'data': data, 'msg': '查询成功！'})

    return jsonify(resp)
